package com.bupt.cosmfl.cosmflweb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bupt.cosmfl.cosmflweb.dao.NodeDao;
import com.bupt.cosmfl.cosmflweb.dto.NodeRegisterDTO;
import com.bupt.cosmfl.cosmflweb.dto.PageDTO;
import com.bupt.cosmfl.cosmflweb.exception.BusinessException;
import com.bupt.cosmfl.cosmflweb.mapper.NodeManageMapper;
import com.bupt.cosmfl.cosmflweb.model.NodeEntity;
import com.bupt.cosmfl.cosmflweb.service.NodeManageService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Author fangtiewei
 * @Date 2021/7/28 16:27
 * @Description
 */
@Service
public class NodeManageServiceImpl implements NodeManageService {
    @Resource
    private NodeManageMapper nodeManageMapper;
    @Resource
    private NodeDao nodeDao;

    @Override
    public IPage<NodeEntity> list(PageDTO dto) {
        IPage<NodeEntity> page = new Page<>(dto.getPageNum(),dto.getPageSize());
        QueryWrapper<NodeEntity> wrapper = new QueryWrapper<>();
        if (dto.getKeyword() != null && StringUtils.isNotBlank(dto.getKeyword())){
            wrapper.like("name",dto.getKeyword());
        }
        try{
            return nodeManageMapper.selectPage(page,wrapper);
        }catch (Exception e){
            throw new BusinessException("select node error: " + e.getMessage());
        }
    }

    @Override
    public Integer registerNode(NodeRegisterDTO dto) {
        NodeEntity nodeEntity = new NodeEntity();
        BeanUtils.copyProperties(dto, nodeEntity);
        int insertNum;
        try {
            insertNum = nodeDao.registerNode(dto.getUserId(), dto.getNodeName(), dto.getIp(), dto.getPort());
        }catch (Exception e){
            throw new BusinessException("insert Node error:" + e.getMessage());
        }
        return insertNum;
    }

    @Override
    public void deleteNode(Long id) {
        nodeDao.deleteNode(id);
    }
}
